#include "Character.h"
#include "global.h"
#include "Downloadable.h"
#include <QString>
#include <QXmlStreamReader>
#include <QDebug>

Character::Character(  )
:Downloadable()
{
	// TODO
}
Character::~Character(  ) 
{
	// TODO
}

void Character::setServer(QString server){
	this->server = server;
}
void Character::setName(QString name){
	this->name = name;
}
QString Character::getUrl(){
	return "http://eu.wowarmory.com/character-sheet.xml?r="+server+"&n="+name;
}

void Character::downloadFinished(QString data){
	QXmlStreamReader xml;
	xml.addData(data);
	while (!xml.atEnd()) {
		QXmlStreamReader::TokenType token = xml.readNext();
		if (token == QXmlStreamReader::StartElement){
			QString name = xml.name().toString();
			if (name == "item"){
				QXmlStreamAttributes attr = xml.attributes(); 
				loadItem(attr);
			}
		}
	}
}

void Character::loadItem(QXmlStreamAttributes& attr){
	QMap<QString, QString> itemMap;
	for (int i=0;i<attr.size();i++){
		QXmlStreamAttribute at = attr[i];
		QString name = at.name().toString();
		QString value = at.value().toString();
		itemMap.insert(name, value);
	}
	int slot = 				intOfMapIndex(itemMap, "slot");
	items[slot].id = 		intOfMapIndex(itemMap, "id");
	items[slot].gem[0].id = intOfMapIndex(itemMap, "gem0Id"); 
	items[slot].gem[1].id = intOfMapIndex(itemMap, "gem1Id"); 
	items[slot].gem[2].id = intOfMapIndex(itemMap, "gem2Id"); 
	items[slot].enchantId = intOfMapIndex(itemMap, "permanentenchant");
	items[slot].download();
}

void Character::recalcStats(){
	intellect=stamina=spirit=spellhaste=spellcrit=spellhitrating=0;
	#define CALC(X)							\
		if(items[i].id>0){					\
			X+=items[i].X;					\
			for (int j = 0;j <3;j++){		\
				if (items[i].gem[j].id>0){	\
					X+=items[i].gem[j].X;	\
				}							\
			}								\
		}
	for(int i=0;i<18;i++){
		CALC(intellect)
		CALC(stamina)
		CALC(spirit) 
		CALC(spellhaste)
		CALC(spellcrit)
		CALC(spellhitrating) 
	}
	#undef CALC
	emit statsUpdated();
}

